package com.example.demopoi.web;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.example.demopoi.config.RoutingWith;
import com.example.demopoi.entity.CarSaleOrder;
import com.example.demopoi.service.TestService;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

@Controller
@Slf4j
public class HomeController {

    @Autowired
    private TestService testService;

    @GetMapping({"", "index"})
    public String index() {
        return "index";
    }

    @GetMapping("test")
    @ResponseBody
    public String test() {

        for (int i = 0; i < 10; i++) {
            testService.executeAsync1(i);
            testService.executeAsync2(i);
        }
        return "test";
    }


    @PostMapping("uploadExcel")
    public String uploadExcel(MultipartFile file) {

        if (!file.isEmpty()) {

            try {
                Workbook workbook = WorkbookFactory.create(file.getInputStream());

                for (int i = 0; i < workbook.getNumberOfSheets(); i++) {
                    Sheet sheet = workbook.getSheetAt(i);
                    String sheetName = sheet.getSheetName();
                    System.out.println(sheetName);
                    JSONArray jsonArray = new JSONArray();
                    for (int j = 1; j < sheet.getPhysicalNumberOfRows(); j++) {
                        Row row = sheet.getRow(j);
                        Cell nameCell = row.getCell(0);
                        Cell countCell = row.getCell(1);

                        JSONObject jsonObject = new JSONObject();
                        jsonObject.put("skuName", nameCell.getStringCellValue());
                        if (countCell.getCellType() == Cell.CELL_TYPE_NUMERIC) {
                            jsonObject.put("count", countCell.getNumericCellValue());
                        } else {
                            jsonObject.put("count", countCell.getStringCellValue());
                        }

                        jsonArray.add(jsonObject);
                    }
                    System.out.println(jsonArray);
                }
            } catch (IOException e) {
                e.printStackTrace();
            } catch (InvalidFormatException e) {
                e.printStackTrace();
            }
        }

        return "index";
    }


    @GetMapping("dataSource")
    @ResponseBody
    @RoutingWith("masterDataSource")
    public String dataSource() {
        return  "html... hello world";
    }
}
